xquery version "3.0";

import module namespace api="api" at "modules/api.xqm";
import module namespace config="http://exist-db.org/xquery/apps/config" at "modules/config.xqm";

declare variable $exist:path external;
declare variable $exist:resource external;
declare variable $exist:controller external;
declare variable $exist:prefix external;
declare variable $exist:root external;

declare %private function local:all-can-read($name){
    let $user-name := xmldb:get-current-user()
    return if ($user-name ne "guest") then
        if ($user-name ne xmldb:get-owner($config:app-root, $name)) then
            starts-with(
                substring(
                    xmldb:permissions-to-string(
                        xmldb:get-permissions($config:app-root, $name)
                    ),
                    7
                ),
                "r"
            )
        else true()
    else false()
};

if ($exist:path eq "/") then
    (: forward root path to index.xql :)
    <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
        <redirect url="index.html"/>
    </dispatch>
else if (starts-with($exist:path, "/api/")) then
    api:request(substring-after(request:get-uri(), "/api/"))
else if (ends-with($exist:resource, ".html")) then
    (: the html page is run through view.xql to expand templates :)
    <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
        <view>
            {
                if (local:all-can-read($exist:resource)) then ()
                else <forward url="{$exist:controller}/login.html" method="get"/>
            }
            <forward url="{$exist:controller}/modules/view.xql"/>
        </view>
		<error-handler>
			<forward url="{$exist:controller}/error-page.html" method="get"/>
			<forward url="{$exist:controller}/modules/view.xql"/>
		</error-handler>
    </dispatch>
else if (starts-with($exist:path, "/good-image/")) then
    response:stream-binary(
        util:string-to-binary(collection("/db/apps/avto-magazin/data/all/goods/")//tovar[@id eq substring-after($exist:path, "/good-image/")]/parameters/image),
        "image/jpg",
        "image.jpg"
    )
(: Requests for javascript libraries are resolved to the file system :)
else if (contains($exist:path, "/libs/")) then
    <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
        <forward url="/{substring-after($exist:path, '/libs/')}" absolute="yes"/>
    </dispatch>
else
    (: everything else is passed through :)
    <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
        <cache-control cache="yes"/>
    </dispatch>
